<template>
    <div class="page animate__animated animate__fadeIn">
        <el-card :bordered="false" shadow="never" class="ivu-mt" :body-style="{ padding: '20px 20px' }">
            <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" size="small">
                <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model="ruleForm.password" autocomplete="off" class="form-input"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="repet_password">
                    <el-input type="password" v-model="ruleForm.repet_password" autocomplete="off" class="form-input"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script>
import { rePwd } from "@/api/login.js";
export default {
    data() {
        var validatePass = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请输入密码"));
            } else {
                if (this.ruleForm.repet_password !== "") {
                    this.$refs.ruleForm.validateField("repet_password");
                }
                callback();
            }
        };
        var validateNewPass = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请再次输入密码"));
            } else if (value !== this.ruleForm.password) {
                callback(new Error("两次输入密码不一致!"));
            } else {
                callback();
            }
        };
        return {
            ruleForm: {
                password: "",
                repet_password: "",
            },
            rules: {
                password: [{ validator: validatePass, trigger: "blur" }],
                repet_password: [
                    { validator: validateNewPass, trigger: "blur" },
                ],
            },
        };
    },
    methods: {
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    rePwd(this.ruleForm).then((res) => {
                        if (res.code == 0) {
                            this.$message({
                                message: res.msg,
                                type: "success",
                            });
                            localStorage.clear();
                            this.$router.replace("/login");
                        } else {
                            this.$message.error(res.msg);
                        }
                    });
                } else {
                    return false;
                }
            });
        },
    },
};
</script>